Skip to content

fix: raise instead of aborting when instantiating pybind11_object - #6244

Open
kroplabeskidu wants to merge 7 commits into
pybind:masterfrom
kroplabeskidu:fix-pybind11-object-new-abort
Open

kroplabeskidu wants to merge 7 commits into
pybind:masterfrom
kroplabeskidu:fix-pybind11-object-new-abort

Conversation

@kroplabeskidu

@kroplabeskidu kroplabeskidu commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Description

Item 11 from #6159. Calling pybind11_object() from Python, or a Python subclass of it with no registered C++ base, aborts the process because a C++ exception reaches the interpreter through the extern "C" tp_new:

terminate called after throwing an instance of 'std::runtime_error'
  what():  instance allocation failed: new instance has no pybind11-registered base types
  • pybind11_object_new now checks for a registered C++ base before it allocates. If there is none, it raises TypeError, so no half-built instance is created.
  • pybind11_object_new sends all other C++ exceptions through try_translate_exceptions(), so they become Python errors (std::bad_alloc becomes MemoryError).
  • make_new_instance checks the tp_alloc result.
  • make_new_instance releases the object if allocate_layout() throws. It does not run tp_dealloc, because the layout is incomplete.
  • pybind11_object_new looks up the type info one time and passes it to make_new_instance and instance::allocate_layout, so construction has no extra lookup.

The new test aborts the test process without this fix. I ran it in both release and debug builds.

A second test makes PyMem_Calloc fail and checks that the instance does not leak.

Suggested changelog entry:

  • Instantiating pybind11_object from Python now raises TypeError instead of aborting the process.

@henryiii
henryiii force-pushed the fix-pybind11-object-new-abort branch from eec0084 to e54d6b1 Compare November 12, 2026 19:40
@henryiii henryiii self-assigned this Nov 13, 2026
@henryiii

Copy link
Copy Markdown
Collaborator

🤖 AI text below 🤖

I pushed bf2e776 on top of your commit. It replaces the cleanup approach with a check before allocation:

  • pybind11_object_new now checks all_type_info(type).empty() before it allocates. If the type has no registered C++ base, it raises TypeError, so no half-built instance is created.
  • The Py_DECREF in make_new_instance is removed. If PyMem_Calloc fails in allocate_layout(), that Py_DECREF runs the full dealloc on an instance with values_and_holders == nullptr, and clear_instance then dereferences null. A subclass __del__ could also run on the partly built object.
  • The clear_instance change is no longer necessary, so I reverted it.
  • All other C++ exceptions go through try_translate_exceptions(), so std::bad_alloc becomes MemoryError (not TypeError) and custom translators apply. Exceptions that are not derived from std::exception can no longer escape and call std::terminate.

Your test is unchanged and still passes. Without the fix, Python aborts on it.

@henryiii

henryiii commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Points to know that are all fine:

  • Leak on allocate_layout() failure: Only for out of memory errors, fine.
  • The abort stays if the module that created internals was built without the fix: nothing in this PR can change that.
  • Translators in tp_new: user-registered exception translators can now run on this path. Fine.

And the only one I could be concerned about:

  • all_type_info(type) runs two times per Python-side construction.

I measured, it's at most 7% for an empty class. If we want to fix it, it's pretty easy, allocate_layout could take the looked-up type. I can't find any usages of this internal function, so I can go ahead and make that change here, but we can drop it if we don't want to and take the small hit. (there's a mutex when reading this, so that's why I think it's worthwhile to keep this to a single read vs. two).

@rwgk

rwgk commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator

— codex on behalf of Ralf —

Preserve CPython's object-destruction bookkeeping on a layout allocation failure. Calling tp_free on a partially initialized instance bypasses the interpreter's normal destruction path. On CPython 3.15.2, with a warmed type cache, my reference-tracer probe saw one CREATE and one DESTROY for normal allocation and teardown. When the existing test helper injected a PyMem_Calloc failure, I got the expected MemoryError but saw one CREATE and zero DESTROY events. On a CPython build with Py_TRACE_REFS, the same path also skips removing the object from the interpreter's reference bookkeeping. Untracking alone is enough to satisfy the existing gc.get_objects() assertion, which explains why both new tests passed locally. Failure path, CPython destruction

One way to handle this is to allocate the non-simple layout before tp_alloc and give it a local owner until it is attached. A plain Py_DECREF on the current failure path would send partially initialized storage through the existing deallocator and could invoke a Python subclass finalizer. There is also a merge conflict in tests/test_class.py with the tests added by #6164.

@henryiii
henryiii force-pushed the fix-pybind11-object-new-abort branch from c0ec259 to 92f5b11 Compare November 28, 2026 15:50
@rwgk

rwgk commented Nov 28, 2026

Copy link
Copy Markdown
Collaborator

— codex on behalf of Ralf —

Handle the null object in the reference-tracer removal event. Starting in CPython 3.14, restoring the original tracer invokes the test's current callback with op == nullptr and PyRefTracer_TRACKER_REMOVED. The callback calls Py_TYPE(op) first. I reproduced the segfault at this head on CPython 3.15.2. Adding op != nullptr before the type check made both targeted tests pass on regular and free-threaded 3.15.2. With that guard, the new regression still fails on the preceding commit with one CREATE and zero DESTROY events. Allocating the layout before the Python object resolves the original finding. Test callback and restore, CPython tracer API, iOS failure

Generated by Codex. Ralf has yet to review these findings.

@henryiii

Copy link
Copy Markdown
Collaborator

🤖 AI text below 🤖

Fixed in 9668a4b: the tracer callback now checks op != nullptr before Py_TYPE(op).

One correction: PyRefTracer_TRACKER_REMOVED is in the 3.15 headers only, not 3.14. The test passed on 3.14.7 without the guard and crashed on 3.15.0. With the guard, test_class.py passes on both.

kroplabeskidu and others added 7 commits November 28, 2026 23:32
Raise TypeError before allocation instead of tearing down a half-built
instance, and translate other C++ exceptions (bad_alloc -> MemoryError).

Assisted-by: ClaudeCode:claude-opus-5-5
Assisted-by: ClaudeCode:claude-fable-5-2
Pass the type info into make_new_instance and instance::allocate_layout.

Assisted-by: ClaudeCode:claude-fable-5-2
Also use a fixed TypeError message, so that PyPy cannot fail while it
makes the qualified type name.

Assisted-by: ClaudeCode:claude-fable-5-2
A failure in allocate_layout() released the object with tp_free. That skipped the interpreter's destruction bookkeeping (reference tracer, Py_TRACE_REFS). The layout storage is now allocated before tp_alloc, so no object exists when the allocation fails.

Assisted-by: ClaudeCode:claude-fable-5-2
CPython 3.15 calls the tracer with a null object for
PyRefTracer_TRACKER_REMOVED when the tracer is replaced.

Assisted-by: ClaudeCode:claude-fable-5-2
@henryiii
henryiii force-pushed the fix-pybind11-object-new-abort branch from 9668a4b to a9178b8 Compare November 29, 2026 04:32

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants